package handlers

import (
	"github.com/gin-gonic/gin"
	"shop-ease/models"
	"strconv"
)

func Create(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	picture := c.PostForm("picture")
	if title == "" || len(title) > 10 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品名称不可为空，并且长度10字以内",
		})
		return
	}
	if content == "" || len(content) > 50 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品详情不可为空，正文内容50字以内",
		})
		return
	}
	n := len(picture)
	if picture[n-3:] == ".jpg" || picture[n-3:] == ".png" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品图片限制jpg、png",
		})
		return
	}
	data := models.Good{
		Title:   title,
		Content: content,
		Picture: picture,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var good []models.Good
	models.DB.Offset(offset).Limit(size).Find(&good)
	var total int64
	models.DB.Model(&models.Good{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查看成功",
		"data":  good,
		"total": total,
	})
}
func Desc(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var good models.Good
	models.DB.Where("id = ?", id).Find(&good)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查看成功",
		"data": good,
	})
}
